#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>

int main()
{
  pid_t id = fork();
  if(id < 0)
  {
    printf("errno: %d,errstring: %s\n",errno,strerror(errno));
    return errno;
  }
  else if(id == 0)
  { 
    int cnt = 3;
    while(cnt)
    {
      printf("子进程运行中，pid：%d\n",getpid());
      cnt--;
      sleep(1);
    }
    exit(123);
  }
  else
  {
    sleep(5);
    
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    
    if(rid > 0)
    {
      if(WIFEXITED(status))
      {
        //两种获取退出码的方法，第一种还可以获取退出信号
        printf("wait sub process success,rid: %d, status code: %d, exit signal: %d\n", rid, (status>>8)&0xFF, status&0x7F);

        printf("wait sub process success,rid: %d, status code: %d\n", rid, WEXITSTATUS(status));
      }
      else
      {
        printf("child process quit error!\n");
      }
    }
    else
    {
      perror("wait fail:");
    }

    while(true)
    {
      printf("我是父进程,pid: %d\n",getpid());
      sleep(1);
    }
  }

  return 0;  
}
